package com.google.code.synchronized_player;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.util.Log;


public class NetReceiver implements Runnable
{
	static final int BUF_MAX_SIZE = 256;
	
	private ServerSocket serverSocket;
	byte[] lengthBuffer = new byte[1];
	byte[] commandBuffer = new byte[BUF_MAX_SIZE];
	boolean isRunning = true;
	
	Controller controller;
	Thread thread;
	
	public NetReceiver(int port, Controller mcontroller) throws IOException 
	{
		controller = mcontroller;
		serverSocket = new ServerSocket(port);
		serverSocket.setReceiveBufferSize(20);
		thread = new Thread(this);
		 thread.setDaemon(true);
		 
		thread.start();
	}
	public void stop()
	{
		isRunning = false;
		thread.stop();
	}
	public void run()
	{
		while ( isRunning)
		{
			try {
				Socket rcv = serverSocket.accept();
				new Thread(new SocketReader(rcv)).start();
			} catch (IOException e) { 
				e.printStackTrace();
			}
		
		}
	}
	
	private class SocketReader implements Runnable {
		
		private final Socket rcv;
		
		public SocketReader(Socket s) {
			rcv = s;
		}

		@Override
		public void run() {
			try {
				InputStream istream = rcv.getInputStream();
				
				istream.read(lengthBuffer, 0, 1); 
				istream.read(commandBuffer, 0, lengthBuffer[0]);
				Command receivedCommand = Command.Parse(commandBuffer, lengthBuffer[0]);
				if (receivedCommand != null)
				{
					controller.EnqueueCommand(receivedCommand);
					Log.d("SynchronizedPlayer", "Parsed: " + new String(commandBuffer,0,lengthBuffer[0],"US-ASCII"));
				}
				else
				{
					Log.d("SynchronizedPlayer", "Can not parse such a command: " + new String(commandBuffer,0,lengthBuffer[0],"US-ASCII"));
				}
			} catch (IOException e) {
				Log.d("SocketReader", e.getMessage());
			} finally {
				try {
					rcv.close();
				} catch (IOException e) {
					Log.d("SocketReader", e.getMessage());
				}
			}
			
		}
		
	}
}
